package cn.chengpengper.rpc.serialization.hessian2;

import cn.chengpengper.rpc.common.exception.SerializerException;
import cn.chengpengper.rpc.serialization.api.Serialization;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class Hessian2Serialization implements Serialization {
    @Override
    public <T> byte[] serialize(T obj) {
        log.info("execute hessian2 serialize");
        if (Objects.isNull(obj)) {
            throw new SerializerException("serialize object is null");
        }
        byte[] result;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final Hessian2Output hessian2Output = new Hessian2Output(bos);
        try {
            hessian2Output.startMessage();
            hessian2Output.writeObject(obj);
            hessian2Output.flush();
            hessian2Output.completeMessage();
            result = bos.toByteArray();
        } catch (IOException e) {
            throw new SerializerException(e.getMessage(), e);
        } finally {
            try {
                hessian2Output.close();
                bos.close();
            } catch (IOException e) {
                throw new SerializerException(e.getMessage(), e);
            }
        }
        return result;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        log.info("execute hessian2 deserialize");
        if (Objects.isNull(data)) {
            throw new SerializerException("deserialize data is null");
        }
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        final Hessian2Input hessian2Input = new Hessian2Input(bis);
        T object;
        try {
            hessian2Input.startMessage();
            object = (T) hessian2Input.readObject();
            hessian2Input.completeMessage();
        } catch (IOException e) {
            throw new SerializerException(e.getMessage(), e);
        } finally {
            try {
                hessian2Input.close();
                bis.close();
            } catch (IOException e) {
                throw new SerializerException(e.getMessage(), e);
            }
        }
        return object;
    }
}
